package com.pox.guli.service.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pox.guli.service.base.dto.CourseDto;
import com.pox.guli.common.base.result.R;
import com.pox.guli.service.edu.entity.*;
import com.pox.guli.service.edu.entity.form.CourseInfoForm;
import com.pox.guli.service.edu.entity.vo.*;
import com.pox.guli.service.edu.feign.OssFeignService;
import com.pox.guli.service.edu.mapper.*;
import com.pox.guli.service.edu.service.CourseService;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author pox21s
 * @since 2022-06-01
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Resource
    private CourseDescriptionMapper courseDescriptionMapper;
    @Resource
    private VideoMapper videoMapper;
    @Resource
    private ChapterMapper chapterMapper;
    @Resource
    private CommentMapper commentMapper;
    @Resource
    private CourseCollectMapper courseCollectMapper;
    @Resource
    private OssFeignService ossFeignService;

    @Override
    public String saveCourseInfo(CourseInfoForm courseInfoForm) {

        Course course = new Course();
        // 通过工具类提取相同属性
        BeanUtils.copyProperties(courseInfoForm, course);
        course.setStatus(Course.COURSE_DRAFT);
        // 存储到数据库
        // 这里是CourseService，因此baseMapper就是CourseMapper
        baseMapper.insert(course);

        // 获取表中的课程描述数据
        String description = courseInfoForm.getDescription();
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setDescription(description);
        // 课程描述中的ID来源于课程表中
        courseDescription.setId(course.getId());

        courseDescriptionMapper.insert(courseDescription);

        return course.getId();
    }

    @Override
    public CourseInfoForm getCourseInfoFormById(String id) {

        CourseInfoForm courseInfoForm = new CourseInfoForm();
        // 组装课程信息表单
        // 获取课程描述信息
        CourseDescription courseDescription = courseDescriptionMapper.selectById(id);
        // 获取课程信息
        Course course = baseMapper.selectById(id);
        // 组装
        BeanUtils.copyProperties(course, courseInfoForm);
        courseInfoForm.setDescription(courseDescription.getDescription());

        return courseInfoForm;
    }

    @Override
    public void updateCourseInfoById(CourseInfoForm courseInfoForm) {

        Course course = new Course();
        // 更新课程信息
        BeanUtils.copyProperties(courseInfoForm, course);
        baseMapper.updateById(course);

        // 更新课程描述
        CourseDescription courseDescription = new CourseDescription();
        BeanUtils.copyProperties(courseInfoForm, courseDescription);
        courseDescription.setId(course.getId());
        courseDescriptionMapper.updateById(courseDescription);
    }

    @Override
    public IPage<CourseVo> selectPage(Long page, Long limit, CourseQueryVo courseQueryVo) {

        // 条件查询，组装条件
        QueryWrapper<CourseVo> queryWrapper = new QueryWrapper<>();
        // 查询结果的排序方式
        queryWrapper.orderByDesc("c.gmt_create");

        // 获取用户传入的查询条件
        String subjectId = courseQueryVo.getSubjectId();
        String subjectParentId = courseQueryVo.getSubjectParentId();
        String teacherId = courseQueryVo.getTeacherId();
        String title = courseQueryVo.getTitle();

        // 条件组装
        if (!StringUtils.isEmpty(subjectId)) {
            queryWrapper.eq("c.subject_id",subjectId);
        }

        if (!StringUtils.isEmpty(subjectParentId)) {
            queryWrapper.eq("c.subject_parent_id",subjectParentId);
        }

        if (!StringUtils.isEmpty(teacherId)) {
            queryWrapper.eq("c.teacher_id",teacherId);
        }

        if (!StringUtils.isEmpty(title)) {
            queryWrapper.eq("c.title",title);
        }

        // 分页
        Page<CourseVo> pageParam = new Page<>(page, limit);
        // 数据库查询
        List<CourseVo> records = baseMapper.selectPageByCourseQueryVo(pageParam, queryWrapper);

        pageParam.setRecords(records);

        return pageParam;
    }

    @Override
    public boolean removeCoverById(String id) {

        Course course = baseMapper.selectById(id);
        if (course != null) {
            String cover = course.getCover();

            if (!StringUtils.isEmpty(cover)) {
                R r = ossFeignService.removeFile(cover);

                return r.getSuccess();
            }
        }

        return false;
    }

    /**
     * 删除课程信息及其相关
     * - 收藏信息
     * - 评论信息
     * - 课时信息
     * - 章节信息
     * - 课程详情
     * - 课程信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeCourseById(String id) {

        // 删除收藏信息
        QueryWrapper<CourseCollect> courseCollectQueryWrapper = new QueryWrapper<>();
        courseCollectQueryWrapper.eq("course_id", id);
        courseCollectMapper.delete(courseCollectQueryWrapper);

        //评论信息：comment
        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
        commentQueryWrapper.eq("course_id", id);
        commentMapper.delete(commentQueryWrapper);

        //课时信息：video
        QueryWrapper<Video> videoQueryWrapper = new QueryWrapper<>();
        videoQueryWrapper.eq("course_id", id);
        videoMapper.delete(videoQueryWrapper);

        //章节信息：chapter
        QueryWrapper<Chapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.eq("course_id", id);
        chapterMapper.delete(chapterQueryWrapper);

        //课程详情：course_description
        courseDescriptionMapper.deleteById(id);

        //课程信息：course
        return this.removeById(id);
    }

    @Override
    public CoursePublishVo getCoursePublishVoById(String id) {

        return baseMapper.selectCoursePublishVoById(id);
    }

    @Override
    public boolean publishCourseById(String id) {

        Course course = new Course();
        course.setId(id);
        // 修改课程发布状态
        course.setStatus(Course.COURSE_NORMAL);

        return this.updateById(course);
    }

    @Override
    public List<Course> webSelectList(WebCourseQueryVo webCourseQueryVo) {
        QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();

        String buyCountSort = webCourseQueryVo.getBuyCountSort();
        String subjectId = webCourseQueryVo.getSubjectId();
        String gmtCreateSort = webCourseQueryVo.getGmtCreateSort();
        String priceSort = webCourseQueryVo.getPriceSort();
        String subjectParentId = webCourseQueryVo.getSubjectParentId();

        // 条件组装
        // 查询课程状态为已发布
        courseQueryWrapper.eq("status", Course.COURSE_NORMAL);

        if (!StringUtils.isEmpty(subjectId)) {
            courseQueryWrapper.eq("subject_id", subjectId);
        }

        if (!StringUtils.isEmpty(subjectParentId)) {
            courseQueryWrapper.eq("subject_parent_id", subjectParentId);
        }

        if (!StringUtils.isEmpty(buyCountSort)) {
            courseQueryWrapper.orderByDesc("buy_count");
        }

        if (!StringUtils.isEmpty(gmtCreateSort)) {
            courseQueryWrapper.orderByDesc("gmt_create");
        }

        if (!StringUtils.isEmpty(priceSort)) {
            if (webCourseQueryVo.getType() == null
                || webCourseQueryVo.getType() == 1) {
                courseQueryWrapper.orderByAsc("price");
            } else {
                courseQueryWrapper.orderByDesc("price");
            }
        }

        return baseMapper.selectList(courseQueryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public WebCourseVo selectWebCourseVoById(String courseId) {
        // 更新课程浏览数
        Course course = baseMapper.selectById(courseId);
        course.setViewCount(course.getViewCount() + 1);
        baseMapper.updateById(course);

        // 获取课程信息
        return baseMapper.selectWebCourseVoById(courseId);
    }

    @Cacheable(value = "index", key = "'selectHotCourse'")
    @Override
    public List<Course> selectHotCourse() {

        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("view_count");
        // 设置返回的个数
        queryWrapper.last("limit 8");

        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public CourseDto getCourseDtoById(String courseId) {

        return baseMapper.selectCourseDtoById(courseId);
    }

    @Override
    public void updateBuyCountById(String id) {

        Course course = baseMapper.selectById(id);
        long buyCount = course.getBuyCount() + 1;
        course.setBuyCount(buyCount);

        baseMapper.updateById(course);
    }

}
